#include "decrypter.h"

/**
 * Decyphers the string s.
 *
 * @param[in]	s              The cyphered data
 * @param[in]	size		      The size of the data.
 *
 * @return	The decyphered data.
 */
static void myDecryptionAlgo (int *s, long size);

/**
 * Compares two letterStat.
 *
 * @param[in]	f1   A letterStat.
 * @param[in]	f2   Another letterStat.
 *
 * @return	Lower than zero if f2 has greater frequency than f1, greater than zero if f1
 *          has greater frequency than f2 or zero if they are equal.
 */
//static int letterStatCmp (const void *f1, const void * f2);

int
checkInput(int argc, char ** argv)
{
	if ( argc != 2)
	{
		printf("Error en el ingreso.\n");
		return -1;
	}
	return 1;
}

int
main(int argc, char ** argv)
{
   int *s;
   long size;
   
   if (checkInput(argc, argv) < 0)
	   return 1;
   
   s = readFile(argv[1], &size);
   
   if ( s == NULL)
   {
	   printf("No se pudo leer el archivo.\n");
   	   return 1;
   }
   
   /*printf("Longitud %ld Mapeo de numeros:\n", size);
   for (i=0; i<size; i++)
      printf("%d\n", s[i]);
   printf("--------------------\n");*/

   myDecryptionAlgo(s, size);

   return 0;
   
}

/*
static int
letterStatCmp (const void *f1, const void * f2)
{
   return (*((letterStat*)f2)).freq - (*((letterStat*)f1)).freq;
}
*/

static void
myDecryptionAlgo (int *s, long size)
{
   alphabetArray cypherFreq;
   
   /* The frequencies are computed */
   computeFrequencies(s, size, &cypherFreq);
   /*int i;
   printf("Frecuencias:\n");
   for (i = 0; i < ALPHABET_NUM; i++)
      printf("%d \t %g\n", cypherFreq[i].c, cypherFreq[i].freq);
   printf("--------------------\n");*/
   
   
   if (checkTransposition(cypherFreq, sortedSpanishFrequencies, TRANSPOSITION_TOP_CHECK, 0.7))
   {
      printf("Ejecuto transposicion!.\n");
      solveTranspo( s,  size);
   }
   else if (checkCesar (cypherFreq, size, 80))
   {
      printf("Ejecuto Cesar!.\n");
      solveCesar(s, size, cypherFreq, NUMBER_SOL);
   }
   else
   {
      printf("Ejecuto Vigenere!.\n");
      solveVigenere(s, size);
   }
   
   free(s);
         
   return;
}
